package com.news.service.impl;

import com.news.model.NewsItem;
import com.news.model.NewsSource;
import com.news.service.NewsFetcher;
import com.news.util.HttpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 今日头条新闻获取器
 */
public class ToutiaoNewsFetcher implements NewsFetcher {
    
    private static final Logger logger = LoggerFactory.getLogger(ToutiaoNewsFetcher.class);
    
    // 今日头条搜索URL
    private static final String TOUTIAO_SEARCH_URL = "https://so.toutiao.com/search";
    private static final String TOUTIAO_HOT_URL = "https://www.toutiao.com/";
    private static final String TOUTIAO_API_SEARCH = "https://so.toutiao.com/search";
    
    @Override
    public NewsSource getSource() {
        return NewsSource.TOUTIAO;
    }
    
    @Override
    public List<NewsItem> fetchHotNews(int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        try {
            logger.info("开始获取今日头条热门新闻");
            
            // 尝试从主页获取热门内容
            String html = HttpUtil.get(TOUTIAO_HOT_URL);
            Document doc = Jsoup.parse(html);
            
            // 解析热门新闻
            newsItems.addAll(parseHotNewsFromHomePage(doc, limit));
            
            // 如果没有获取到足够数据，使用备用方法
            if (newsItems.size() < limit / 2) {
                newsItems.addAll(getToutiaoHotNewsBackup(limit - newsItems.size()));
            }
            
            logger.info("成功获取今日头条热门新闻 {} 条", newsItems.size());
            
        } catch (Exception e) {
            logger.error("获取今日头条热门新闻失败", e);
            // 使用备用数据
            newsItems.addAll(getToutiaoHotNewsBackup(limit));
        }
        
        return newsItems.subList(0, Math.min(newsItems.size(), limit));
    }
    
    /**
     * 从主页解析热门新闻
     */
    private List<NewsItem> parseHotNewsFromHomePage(Document doc, int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        try {
            // 查找新闻条目的多种可能选择器
            String[] selectors = {
                ".feed-card",
                ".article-item",
                ".news-item",
                "[data-item-id]",
                ".item"
            };
            
            for (String selector : selectors) {
                Elements articles = doc.select(selector);
                if (!articles.isEmpty()) {
                    logger.debug("使用选择器 {} 找到 {} 个元素", selector, articles.size());
                    
                    int count = 0;
                    for (Element article : articles) {
                        if (count >= limit) break;
                        
                        try {
                            NewsItem newsItem = parseArticleElement(article);
                            if (newsItem != null) {
                                newsItems.add(newsItem);
                                count++;
                            }
                        } catch (Exception e) {
                            logger.debug("解析文章元素失败: {}", e.getMessage());
                        }
                    }
                    
                    if (newsItems.size() > 0) {
                        break; // 如果成功解析到内容就退出
                    }
                }
            }
            
        } catch (Exception e) {
            logger.warn("解析今日头条主页失败", e);
        }
        
        return newsItems;
    }
    
    /**
     * 解析单个文章元素
     */
    private NewsItem parseArticleElement(Element article) {
        try {
            // 查找标题
            Element titleElement = article.select("a").first();
            if (titleElement == null) {
                titleElement = article.select(".title, .headline, h3, h2").first();
            }
            
            if (titleElement == null) return null;
            
            String title = titleElement.text().trim();
            if (title.isEmpty() || title.length() < 5) return null;
            
            // 获取链接
            String link = titleElement.attr("href");
            if (link.isEmpty()) {
                link = article.select("a").first().attr("href");
            }
            
            // 处理相对链接
            if (link.startsWith("/")) {
                link = "https://www.toutiao.com" + link;
            } else if (!link.startsWith("http")) {
                link = "https://www.toutiao.com/" + link;
            }
            
            // 查找摘要/内容
            String content = "";
            Element contentElement = article.select(".abstract, .summary, .desc, p").first();
            if (contentElement != null) {
                content = contentElement.text().trim();
            }
            
            // 查找作者
            String author = "";
            Element authorElement = article.select(".source, .author, .media-name").first();
            if (authorElement != null) {
                author = authorElement.text().trim();
            }
            
            NewsItem newsItem = new NewsItem();
            newsItem.setTitle(title);
            newsItem.setContent(content.isEmpty() ? "今日头条 - " + title : content);
            newsItem.setSource(NewsSource.TOUTIAO.getDisplayName());
            newsItem.setUrl(link);
            newsItem.setPublishTime(LocalDateTime.now());
            newsItem.setCategory("头条热点");
            newsItem.setHotScore(9000 + (int)(Math.random() * 1000));
            newsItem.setAuthor(author.isEmpty() ? "今日头条" : author);
            
            return newsItem;
            
        } catch (Exception e) {
            logger.debug("解析文章元素失败", e);
            return null;
        }
    }
    
    @Override
    public List<NewsItem> searchNews(String keyword, int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        try {
            logger.info("开始搜索今日头条新闻，关键词: {}", keyword);
            
            // 构建搜索URL，类似用户截图的搜索格式
            String encodedKeyword = java.net.URLEncoder.encode(keyword, "UTF-8");
            String searchUrl = TOUTIAO_SEARCH_URL + "?dvpf=pc&source=input&keyword=" + encodedKeyword;
            
            logger.debug("今日头条搜索URL: {}", searchUrl);
            
            String html = HttpUtil.get(searchUrl);
            Document doc = Jsoup.parse(html);
            
            // 解析搜索结果
            newsItems.addAll(parseSearchResults(doc, keyword, limit));
            
            // 如果没有获取到足够结果，提供备用搜索结果
            if (newsItems.isEmpty()) {
                newsItems.addAll(getMockToutiaoSearchResults(keyword, limit));
            }
            
            logger.info("今日头条搜索完成，获取结果 {} 条", newsItems.size());
            
        } catch (Exception e) {
            logger.error("搜索今日头条新闻失败，关键词: {}", keyword, e);
            // 提供备用搜索结果
            newsItems.addAll(getMockToutiaoSearchResults(keyword, limit));
        }
        
        return newsItems;
    }
    
    /**
     * 解析搜索结果
     */
    private List<NewsItem> parseSearchResults(Document doc, String keyword, int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        try {
            // 搜索结果的可能选择器
            String[] selectors = {
                ".result-content",
                ".search-result",
                ".search-item",
                ".result-item",
                "[data-log]"
            };
            
            for (String selector : selectors) {
                Elements results = doc.select(selector);
                if (!results.isEmpty()) {
                    logger.debug("搜索结果使用选择器: {}, 找到 {} 个结果", selector, results.size());
                    
                    int count = 0;
                    for (Element result : results) {
                        if (count >= limit) break;
                        
                        try {
                            NewsItem newsItem = parseSearchResultElement(result, keyword);
                            if (newsItem != null) {
                                newsItems.add(newsItem);
                                count++;
                            }
                        } catch (Exception e) {
                            logger.debug("解析搜索结果失败: {}", e.getMessage());
                        }
                    }
                    
                    if (newsItems.size() > 0) {
                        break;
                    }
                }
            }
            
        } catch (Exception e) {
            logger.warn("解析今日头条搜索结果失败", e);
        }
        
        return newsItems;
    }
    
    /**
     * 解析单个搜索结果元素
     */
    private NewsItem parseSearchResultElement(Element result, String keyword) {
        try {
            // 查找标题
            Element titleElement = result.select("a[href], .title a, h3 a, .headline a").first();
            if (titleElement == null) return null;
            
            String title = titleElement.text().trim();
            if (title.isEmpty() || title.length() < 3) return null;
            
            // 获取链接
            String link = titleElement.attr("href");
            if (link.startsWith("/")) {
                link = "https://www.toutiao.com" + link;
            } else if (!link.startsWith("http")) {
                return null; // 无效链接
            }
            
            // 查找内容摘要
            String content = "";
            Element contentElement = result.select(".abstract, .summary, .content, .desc").first();
            if (contentElement != null) {
                content = contentElement.text().trim();
            }
            
            // 查找发布时间
            String timeStr = "";
            Element timeElement = result.select(".time, .publish-time, .date").first();
            if (timeElement != null) {
                timeStr = timeElement.text().trim();
            }
            
            // 查找来源
            String source = "";
            Element sourceElement = result.select(".source, .media, .author").first();
            if (sourceElement != null) {
                source = sourceElement.text().trim();
            }
            
            NewsItem newsItem = new NewsItem();
            newsItem.setTitle(title);
            newsItem.setContent(content.isEmpty() ? "搜索结果 - " + title : content);
            newsItem.setSource(NewsSource.TOUTIAO.getDisplayName());
            newsItem.setUrl(link);
            newsItem.setPublishTime(LocalDateTime.now());
            newsItem.setCategory("搜索结果");
            newsItem.setHotScore(8500 + (int)(Math.random() * 500));
            newsItem.setAuthor(source.isEmpty() ? "今日头条" : source);
            
            return newsItem;
            
        } catch (Exception e) {
            logger.debug("解析搜索结果元素失败", e);
            return null;
        }
    }
    
    /**
     * 备用今日头条热门新闻
     */
    private List<NewsItem> getToutiaoHotNewsBackup(int limit) {
        List<NewsItem> newsItems = new ArrayList<>();
        
        String[] hotTopics = {
            "科技创新引领未来发展新趋势",
            "经济形势分析：市场走向预测",
            "教育改革新政策正式实施",
            "医疗健康：新技术助力精准治疗",
            "环保行动：绿色发展成效显著",
            "文化传承：传统艺术焕发新活力",
            "体育赛事：精彩比赛引人关注",
            "国际新闻：全球合作共促发展",
            "社会民生：民众关心的热点话题",
            "科学发现：最新研究成果发布"
        };
        
        for (int i = 0; i < Math.min(limit, hotTopics.length); i++) {
            NewsItem newsItem = new NewsItem();
            newsItem.setTitle(hotTopics[i]);
            newsItem.setContent("今日头条热点 - " + hotTopics[i] + "。这是详细的新闻内容摘要...");
            newsItem.setSource(NewsSource.TOUTIAO.getDisplayName());
            newsItem.setUrl("https://www.toutiao.com/search?keyword=" + hotTopics[i]);
            newsItem.setPublishTime(LocalDateTime.now().minusMinutes(i * 15));
            newsItem.setCategory("头条热点");
            newsItem.setHotScore(9500 - i * 50);
            newsItem.setAuthor("今日头条");
            
            newsItems.add(newsItem);
        }
        
        return newsItems;
    }
    
    /**
     * 模拟搜索结果
     */
    private List<NewsItem> getMockToutiaoSearchResults(String keyword, int limit) {
        List<NewsItem> mockResults = new ArrayList<>();
        
        String[] resultTemplates = {
            keyword + "最新动态：权威解读",
            keyword + "深度分析：专家观点",
            keyword + "相关报道：全面覆盖", 
            keyword + "热点讨论：网友关注",
            keyword + "实时更新：最新消息"
        };
        
        for (int i = 0; i < Math.min(limit, resultTemplates.length); i++) {
            NewsItem newsItem = new NewsItem();
            newsItem.setTitle(resultTemplates[i]);
            newsItem.setContent("关于\"" + keyword + "\"的搜索结果。由于网络限制，暂时显示模拟内容。");
            newsItem.setSource(NewsSource.TOUTIAO.getDisplayName());
            newsItem.setUrl("https://so.toutiao.com/search?dvpf=pc&source=input&keyword=" + keyword);
            newsItem.setPublishTime(LocalDateTime.now());
            newsItem.setCategory("搜索结果");
            newsItem.setHotScore(8000 - i * 100);
            newsItem.setAuthor("今日头条搜索");
            
            mockResults.add(newsItem);
        }
        
        logger.info("提供今日头条模拟搜索结果 {} 条", mockResults.size());
        return mockResults;
    }
    
    @Override
    public boolean isAvailable() {
        try {
            boolean accessible = HttpUtil.isAccessible("https://www.toutiao.com");
            logger.debug("今日头条服务可用性检查结果: {}", accessible);
            return accessible;
        } catch (Exception e) {
            logger.warn("今日头条服务可用性检查失败: {}", e.getMessage());
            return false;
        }
    }
} 